/**
 * 指标区域配置、模板指标配置、模板指标关系配置、指标展示相关
 */
import {
  getRangeInfo, //获取区域接口
  getRangeAdd, //保存区域接口新增
  getRangeEdit, //保存区域接口修改
  getReportItemInfo, //获取指标配置接口
  editTemplateItem, //指标模板关系-批量处理
  getReportMeta, //报表下拉接口
  getReportMetaInfo, //根据报表ID和指标代码获取信息接口参数bbid
  getReportTargetList, // 指标列表 搜索接口
  getReportDataList, //获取渲染数据
  setReportDataEditInfo, //修改渲染数据
  addReportMeta, // 指标新增
  deleteReportItems, // 指标删除
  deleteReportItem,
} from '@/api/websheet.js'
import {
  columns,
  targetRuleColumns,
} from '../export'

export const ZbMixin = {
  data() {
    return {
      data: [],
      columns,
      detail: {},
      tableData: [],
      loading: false,
      formSearch: this.$form.createForm(this, { name: 'formSearch' }),
      pagination: {}, //指标分页
      visibleMechanism: false,//打开新建指标弹框
      confirmLoading: false,//新建指标loading
      targetLoading: false,
      sheetList: [], //渲染数据
      targetList: [],
      autoTarget: {},
      rangeSys: false,
      rangeInfo: { info: {}, range: [] }, //区域列表
      historyRangeInfo: { info: {}, range: [] }, //历史区域列表
      targetRule: {}, //指标规则配置
      validatorTargetRules: {
        rangeId: [{ required: false, message: '请选择区域!' }],
        syfw: [{ required: false, message: '请选择适用范围!' }],
        yzzd: [{ required: false, message: '请选择验证字段!' }],
        gltj: [{ required: true, message: '请填写筛选条件!' }],
        yzgs: [{ required: true, message: '请填写验证公式!' }],
        tssm: [{ required: true, message: '请填写提示说明!' }],
        bz: [{ required: false, message: '请填写备注!' }],
        bjys: [{ required: false, message: '请填写背景颜色!' }],
      },
      targetRuleList: [], //指标规则列表
      targetRuleItem: {}, //指标规则详情
      targetRuleColumns,
    }
  },
  created() {
  },
  methods: {
    //打开新建指标弹框
    showModalMechanism() {
      this.visibleMechanism = true
    },
    //新建指标提交
    handleSubmitMechanism(values) {
      this.confirmLoading = true
      addReportMeta(values).then((res) => {
        if (res.code === 200) {
          this.visibleMechanism = false
          this.$message.success('新建成功')
          if (this.detail && (this.detail.r || this.detail.row_focus)) {
            let value = luckysheet.getCellValue(this.detail.r, this.detail.c)
            if (!value) {
              this.handleDouble({ zbdm: res.result ? values.zbdm : '', bbdm: values.bbdm })
            }
          }
          this.queryReportItemInfo(this.exportJson, false)
        } else {
          this.$message.warning('服务器出错')
        }
        this.confirmLoading = false
      })
    },
    // 获取指标值渲染数据
    queryReportDataList(record) {
      this.zbLoading = true
      getReportDataList({
        bbdm: this.parameter.bbdm,
        bbpc: this.parameter.bbpc,
        ssjg: this.parameter.ssjg,
        frdm: this.parameter.frdm,
      }).then((res) => {
        if (res.code === 200) {
          let list = res.result || []
          this.sheetList = list
          if (record && list.length > 0) {
            setTimeout(() => {
              this.loop(30, 1, list)
            }, 500)
          } else {
            this.zbLoading = false
          }
        } else {
          this.zbLoading = false
          this.$message.warning('服务器出错!')
        }

      })
    },
    // 指标分页
    pageChange(page) {
      this.formSearch.validateFields((error, values) => {
        if (!error) {
          this.queryReportTargetList({ ...values, pageNo: page })
        }
      })
    },
    // 清空指标搜索条件
    handleReset() {
      this.queryReportTargetList({ bbdm: this.exportJson.bbdm })
      this.formSearch.resetFields()
    },
    // 搜索指标
    handleSearch(e) {
      e.preventDefault()
      this.formSearch.validateFields((error, values) => {
        if (!error) {
          this.queryReportTargetList({ ...values, bbdm: this.exportJson.bbdm })
        }
      })
    },
    // 数据循环渲染到Excel
    loop(index, num, list) {
      list.map((item, i) => {
        if (
          (typeof item.hh === 'number' || (typeof item.hh === 'string' && item.hh !== '')) &&
          (typeof item.lh === 'number' || (typeof item.lh === 'string' && item.lh !== ''))
        ) {
          // let data = this.calcChain.filter((el) => el.r == item.hh && el.c == item.lh)[0] || {}
          // let dataF = {}
          // if (data && data.func) {
          //   dataF.f = data.func[2]
          // } else {
          // }
          // let obj = this.influenceFunc[`${item.hh}${item.lh}`]
          const ruleItem = this.targetRuleFilter.filter(el => el.gltj === item.zbdm) || [];
          const ps = ruleItem.length > 0 ? {
            //批注
            left: null, //批注框左边距
            top: null, //批注框上边距
            width: null, //批注框宽度
            height: null, //批注框高度
            value: ruleItem[0].tssm, //批准内容
            isshow: false, //批注框为显示状态
          } : {};
          if (ps.value) {
            luckysheet.setCellFormat(item.hh - 0, item.lh - 0, 'ps', ps)
          }
          let isFn = this.calcChain.some((el) => el.r == item.hh && el.c == item.lh)
          // 验证公式
          if (ruleItem.length > 0 && ruleItem[0].yzgs) {
            let str = ruleItem[0].yzgs
            let strList = str ? str.indexOf('n(') > -1 ? str
              .replace(/(n\()/g, '')
              .replace(/\)/g, '').trim()
              .split(',') : str.indexOf('s(') > -1 ? [str] : [] : []
            let status = []
            let value = item.zbsz - 0
            strList.map((item) => {
              if (item.indexOf('gt') > -1) {
                status.push(value > parseFloat(item.replace(/\-gt/g, '')))
              } else if (item.indexOf('lt') > -1) {
                status.push(value < parseFloat(item.replace(/\-lt/g, '')))
              } else if (item.indexOf('ge') > -1) {
                status.push(value >= parseFloat(item.replace(/\-ge/g, '')))
              } else if (item.indexOf('le') > -1) {
                status.push(value <= parseFloat(item.replace(/\-le/g, '')))
              } else if (item.indexOf('eq') > -1) {
                status.push(value == parseFloat(item.replace(/\-eq/g, '')))
              } else if (item.indexOf('ne') > -1) {
                status.push(value != parseFloat(item.replace(/\-ne/g, '')))
              } else if (item.indexOf('s(') > -1) {
                if (item.indexOf(value) > -1) {
                  status.push(true)
                }
              } else {
                status.push(true)
              }
            })
            if (this.parameter && this.parameter.readonly === '0' && this.parameter.type === 'render' && !isFn) {
              if (status.some((item) => item === true)) {
                luckysheet.setCellFormat(item.hh, item.lh, 'bg', '#FF0000')
              } else {
                luckysheet.setCellFormat(item.hh, item.lh, 'bg', '#1890FF')
              }
              luckysheet.setCellFormat(item.hh, item.lh, 'fc', '#ffffff')
            }
          }
          if (!isFn) {
            if (!(ruleItem.length > 0 && ruleItem[0].yzgs) && item.sfyz === '1' && this.parameter && this.parameter.readonly === '0' && this.parameter.type === 'render') {
              luckysheet.setCellFormat(item.hh, item.lh, 'bg', '#1890FF')
              luckysheet.setCellFormat(item.hh, item.lh, 'fc', '#ffffff')
            }
            window.luckysheet.setCellValue(
              item.hh - 0,
              item.lh - 0,
              { v: item.zbsz, m: item.zbsz, editInfo: item },
              {
                isRefresh: i === list.length - 1,
              }
            )
          }
          luckysheet.setCellFormat(item.hh, item.lh, 'ct', {
            "fa": "0.00",
            "t": "n"
          })
        }
      })
      let newList = this.sheetList.slice(index * num, (num + 1) * index)
      if (newList.length > 0) {
        setTimeout(() => {
          this.loop(index, num + 1, newList)
        }, 50)
      } else {
        if (this.type === 'render') {
          this.zbLoading = false
          luckysheet.refreshFormula()
        }
        setTimeout(() => {
          this.queryReportItemInfo({ bbdm: this.parameter.bbdm }, false)
        }, 200)
      }
    },
    // 获取区域配置信息
    queryRangeInfo(item) {
      getRangeInfo({ bbdm: item.bbdm, mbbm: item.mbbm }).then((res) => {
        if (res.code === 200) {
          const data = res.result.records[0] || {}
          const range = data.yxqy ? JSON.parse(data.yxqy) : []
          const item = { info: data, range: range }
          this.rangeInfo = JSON.parse(JSON.stringify(item))
          this.historyRangeInfo = JSON.parse(JSON.stringify(item))
          if (range.length > 0 && this.type === 'target') {
            setTimeout(() => {
              this.drawRange(range)
            }, 500)
          }
        } else {
          this.$message.warning('服务器出错!')
        }
      })
    },
    // 获取报表下拉列表
    queryReportMeta() {
      getReportMeta().then((res) => {
        if (res.code === 200) {
          this.tableData = res.result || []
        } else {
          this.$message.warning('服务器出错!')
        }
      })
    },
    // 获取指标列表
    queryReportTargetList(item) {
      getReportTargetList(item).then((res) => {
        if (res.code === 200) {
          this.loading = false
          this.data = res.result.records || []
          this.pagination = {
            current: res.result.current,
            total: res.result.total,
          }
        } else {
          this.$message.warning('服务器出错!')
        }
      })
    },
    // 获取指标配置自动带入信息
    queryReportMetaInfo(record) {
      this.targetLoading = true
      getReportMetaInfo({ bbdm: record.bbdm, zbdm: record.zbdm }).then((res) => {
        if (res.code === 200) {
          this.autoTarget = res.result || {}
          let range = {
            row: [record.hh - 0 || this.detail.r - 0, record.hh - 0 || this.detail.r - 0],
            column: [record.lh - 0 || this.detail.c - 0, record.lh - 0 || this.detail.c - 0],
          }
          let data = luckysheet.getRangeValue({ range })[0][0]
          this.detail = { ...this.detail, ...data }
        } else {
          this.autoTarget = {}
          this.$message.warning('服务器出错!')
        }
        this.targetLoading = false
      })
    },
    // 获取指标配置列表
    queryReportItemInfo(record, status) {
      getReportItemInfo({ bbdm: record.bbdm, pageSize: 500 }).then((res) => {
        if (res.code === 200) {
          let list = res.result.records || []
          this.targetList = list
          if (status) {
            list.map((item, index) => {
              if (item.hh && item.lh) {
                let range = { row: [item.hh - 0, item.hh - 0], column: [item.lh - 0, item.lh - 0] }
                let data = luckysheet.getRangeValue({ range })[0][0] || {}
                if (this.type === 'target') {
                  data.v = item.zbmc
                  data.m = item.zbmc
                }
                // if (this.type === 'render' && this.calcChain.length > 0) {
                //   let dataF = this.calcChain.filter((el) => el.r == item.hh && el.c == item.lh)[0] || {}
                //   data.f = dataF && dataF.func ? dataF.func[2] : null
                //   delete data.v
                // }
                luckysheet.setRangeValue(
                  [
                    [
                      {
                        ...data,
                        targetInfo: item,
                      },
                    ],
                  ],
                  {
                    range: range,
                    order: 0,
                    isRefresh: index === list.length - 1,
                    success: function () {
                      console.log('成功')
                    },
                  }
                )
              }
            })
            if (this.type === 'render' && this.calcChain.length > 0) {
              setTimeout(() => {
                luckysheet.refreshFormula()
              }, 200)
            }
            if (this.type === 'target') {
              this.queryReportParam()
            }
          }
        } else {
          this.$message.warning('服务器出错!')
        }
      })
    },
    //添加修改指标模板关系
    editReportItem(hasId = [], record) {
      editTemplateItem(hasId).then((res) => {
        if (res.code === 200) {
          this.queryReportItemInfo(this.exportJson, true)
          this.queryReportMetaInfo(record)
          this.$message.success('指标配置成功')
        } else {
          this.$message.warning('服务器出错!')
        }
      })
    },
    // 双击选择指标
    handleDouble(record) {
      if (this.detail && (this.detail.r || this.detail.row_focus)) {
        // let data = {
        //   hh: this.detail.r || this.detail.row_focus,
        //   lh: this.detail.c || this.detail.column_focus,
        // }
        // let itemData = {
        //   bbdm: this.exportJson.bbdm,
        //   zbdm: record.zbdm,
        //   mbbm: this.exportJson.mbbm,
        //   ...data,
        // }
        // let hasId = []
        // let noHasId = []
        // if (this.targetList.some((item) => item.hh == data.hh && item.lh == data.lh)) {
        //   let item = this.targetList.filter((item) => item.hh == data.hh && item.lh == data.lh)[0] || {}
        //   hasId.push({ ...itemData, ...item })
        // } else {
        //   noHasId.push(itemData)
        // }
        // if (this.detail && this.detail.f) {
        //   this.analyticalFnfluence(record, this.detail, hasId, noHasId)
        // } else {
        //   this.editReportItem(hasId, noHasId, record)
        // }
        // dataFilter
        let data = {
          hh: this.detail.r || this.detail.row_focus,
          lh: this.detail.c || this.detail.column_focus,
        }
        let itemData = {
          bbdm: this.exportJson.bbdm,
          zbdm: record.zbdm,
          mbbm: this.exportJson.mbbm,
          ...data,
        }
        this.editReportItem([itemData], record)
      } else {
        this.$message.warning('请先选择一个配置区域')
      }
    },
    // 双击选中指标配置关联表
    customRow(record, index) {
      return {
        on: {
          // 事件
          dblclick: (event) => {
            if (this.targetLoading) {
              this.$message.warning('正在拉取数据，请稍后')
              return
            }
            this.handleDouble(record)
          },
        },
      }
    },
    //开始修改区域配置
    editRange() {
      if (this.rangeSys) {
        this.rangeInfo = JSON.parse(JSON.stringify(this.historyRangeInfo))
        const range = JSON.parse(JSON.stringify(this.historyRangeInfo.range))
        luckysheet.setRangeShow(range, {
          show: true,
          order: this.historyRangeInfo.info.order || '0',
        })
        this.rangeSys = false
      } else {
        this.rangeSys = true
        this.rangeInfo = JSON.parse(JSON.stringify(this.historyRangeInfo))
      }
    },
    //保存区域配置
    saveRange(history, list, status) {
      this.rangeSys = false
      if (history) {
        this.historyRangeInfo = JSON.parse(JSON.stringify(history))
        this.rangeInfo = JSON.parse(JSON.stringify(history))
        this.drawRange(history.range)
        luckysheet.setRangeShow(history.range, {
          show: false,
          order: this.historyRangeInfo.info.order || '0',
        })
        return
      }
      const item = {
        bbdm: this.exportJson.bbdm,
        mbbm: this.exportJson.mbbm,
        yxqy: JSON.stringify(list),
      }
      if (this.historyRangeInfo.info.id) {
        getRangeEdit({ id: this.historyRangeInfo.info.id, ...item }).then((res) => {
          if (res.code === 200) {
            const data = res.result[0] || {}
            const range = data.yxqy ? JSON.parse(data.yxqy) : []
            const item = { info: data, range: range }
            this.rangeInfo = JSON.parse(JSON.stringify(item))
            this.historyRangeInfo = JSON.parse(JSON.stringify(item))
            if (list && list.length > 0 && !status) {
              this.drawRange(list)
            }
            this.$message.success('修改区域配置成功')
          } else {
            this.$message.warning('服务器出错!')
          }
        })
      } else {
        getRangeAdd(item).then((res) => {
          if (res.code === 200) {
            const data = res.result[0] || {}
            const range = data.yxqy ? JSON.parse(data.yxqy) : []
            const item = { info: data, range: range }
            this.rangeInfo = JSON.parse(JSON.stringify(item))
            this.historyRangeInfo = JSON.parse(JSON.stringify(item))
            this.$message.success('保存区域配置成功')
          } else {
            this.$message.warning('服务器出错!')
          }
        })
      }
    },
    //指标数据批量更新数据
    updateReportDataEditInfos(list) {
      let allList = []
      list.map((item) => {
        let newList = this.editReportDataEditInfo(item)
        newList.map((el) => {
          if (allList.some((record) => record.zbdm === el.zbdm)) {
            allList.map((record) => {
              if (record.zbdm === el.zbdm) {
                record.zbsz = el.zbsz
              }
            })
          } else {
            allList.push(el)
          }
        })
      })
      this.updateReportDataEditInfo(allList)
    },
    //修改指标值及影响的公式值
    editReportDataEditInfo(newValue) {
      let list = []
      if (newValue && newValue.targetInfo) {
        //当前修改的单元格
        list = [{ ...newValue.editInfo, zbsz: newValue.v === null ? '' : newValue.v }]
        if (newValue.targetInfo.influence) {
          //影响到公式的单元格
          let newList = this.loopInfluence(JSON.parse(newValue.targetInfo.influence))
          list = [...list, ...newList]
        }
      }
      return list
    },
    // 寻找关联公式数据
    loopInfluence(influence) {
      let list = []
      influence.map((item) => {
        let value = luckysheet.getCellValue(item.position.hh, item.position.lh)
        let data = this.sheetList.filter(
          (el) =>
            (typeof el.hh === 'number' || (typeof el.hh === 'string' && el.hh !== '')) &&
            (typeof el.lh === 'number' || (typeof el.lh === 'string' && el.lh !== '')) &&
            el.hh == item.position.hh &&
            el.lh == item.position.lh
        )[0]
        data.zbsz = value
        list.push(data)
      })
      return list
    },
    // 指标数据更新单元格信息
    updateReportDataEditInfo(list) {
      setReportDataEditInfo(list).then((res) => {
        if (res.code === 200) {
          this.queryReportDataList()
          this.$message.success('修改成功!')
        } else {
          this.$message.warning('服务器出错!')
        }
        this.dataIEditStatus = true
      })
    },
    // 指标配置删除
    deleteZbpz(record) {
      let range = { row: [record.r - 0, record.r - 0], column: [record.c - 0, record.c - 0] }
      record = luckysheet.getRangeValue({ range })[0][0]
      // if (record.targetInfo && record.targetInfo.influence) {
      //   let ids = [record.targetInfo.id]
      //   let influence = JSON.parse(record.targetInfo.influence)
      //   let list = [record.targetInfo]
      //   influence.map((el) => {
      //     let data = this.targetList.filter((item) => item.hh == el.position.hh && item.lh == el.position.lh)[0]
      //     if (data && data.id) {
      //       list.push(data)
      //       ids.push(data.id)
      //     }
      //   })
      //   deleteReportItems({ ids: ids.join(',') }).then((res) => {
      //     if (res.code === 200) {
      //       list.map((item, index) => {
      //         let range = { row: [item.hh - 0, item.hh - 0], column: [item.lh - 0, item.lh - 0] }
      //         let data = luckysheet.getRangeValue({ range })
      //         delete data.targetInfo
      //         luckysheet.setRangeValue(
      //           [
      //             [
      //               {
      //                 ...data[0][0],
      //                 m: '',
      //                 v: '',
      //               },
      //             ],
      //           ],
      //           {
      //             range: range,
      //             order: 0,
      //             isRefresh: index === list.length - 1,
      //           }
      //         )
      //       })
      //       this.autoTarget = {}
      //       this.queryReportItemInfo(this.exportJson)
      //       this.$message.success('删除成功')
      //     } else {
      //       this.$message.warning('服务器出错!')
      //     }
      //   })
      //   return
      // }
      deleteReportItem({ id: record.targetInfo.id }).then((res) => {
        if (res.code === 200) {
          let data = luckysheet.getRangeValue({ range })[0][0]
          delete data.targetInfo
          luckysheet.setRangeValue(
            [
              [
                {
                  ...data,
                  m: '',
                  v: '',
                },
              ],
            ],
            {
              range: range,
              order: 0,
              isRefresh: true,
            }
          )
          this.autoTarget = {}
          this.queryReportItemInfo(this.exportJson)
          this.$message.success('删除成功')
        } else {
          this.$message.warning('服务器出错!')
        }
      })
    },
  }
}